package ua.kharkov.photo.dal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Component;

import ua.kharkov.photo.model.User;
import ua.kharkov.photo.model.UserToRegister;

@Component
public class JDBCUserRepository extends AbstractRepository implements
		UserRepository {

	private static final String AUTHORIZE_USER_QUERY = "SELECT count(*) FROM photogallery_users WHERE user_name = :username AND password = :password";
	private static final String IS_USER_EXIST_QUERY = "SELECT * FROM photogallery_users WHERE user_name = :username";
	private static final String GET_ALL_USERS_QUERY = "SELECT * FROM photogallery_users";
	private static final String REGISTER_USER_QUERY = "INSERT INTO photogallery_users"
			+ "(user_name, password, ID) VALUES (:user_name, :password, :id)";

	@Override
	public void registerUser(UserToRegister user) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("user_name", user.getRegistrationUserName());
		parameters.put("password", user.getRegistrationPassword());
		parameters.put("id", 0);

		namedParameterJdbcTemplate.update(REGISTER_USER_QUERY, parameters);
	}

	@Override
	public boolean autorizeUser(final User user) {
		int userConut = namedParameterJdbcTemplate.queryForObject(
				AUTHORIZE_USER_QUERY, new HashMap<String, String>() {
					{
						put("username", user.getUserName());
						put("password", user.getPassword());
					}
				}, Integer.class);

		return userConut == 1;
	}

	@Override
	public boolean isUserExist(final String userName) {
		int userConut = namedParameterJdbcTemplate.queryForObject(
				IS_USER_EXIST_QUERY, new HashMap<String, String>() {
					{
						put("username", userName);
					}
				}, Integer.class);

		return userConut == 1;
	}

	@Override
	public List<User> getAllUsers() {
		List<User> users = namedParameterJdbcTemplate.query(
				GET_ALL_USERS_QUERY,
				ParameterizedBeanPropertyRowMapper.newInstance(User.class));

		return users;
	}
}